import { Inject, Provide } from "@midwayjs/core";
import { Repository } from "typeorm";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Utils } from "../utils";
import { BblHomeSection } from "../entity/home.section.entity";
import { BblHomeBanner } from "../entity/home.banner.entity";
import { BblHomeContent } from "../entity/home.content.entity";
import { AttachService } from "./att.service";
import {
  SectionCreateDto,
  ContentCreateDto,
  BannerCreateDto,
  SectionDto
} from "../dto/home.dto";
import { AttachDto } from "../dto/att.dto";
import { ContentDto } from "../dto/home.dto";

@Provide()
export class HomeService {
  @Inject()
  utils: Utils;

  @Inject()
  attService: AttachService;

  @InjectEntityModel(BblHomeSection)
  sectionModel: Repository<BblHomeSection>;

  @InjectEntityModel(BblHomeBanner)
  bannerModel: Repository<BblHomeBanner>;

  @InjectEntityModel(BblHomeContent)
  contentModel: Repository<BblHomeContent>;

  async add_home_section(dto: SectionCreateDto) {
    const section = new BblHomeSection();
    section.sectionId = this.utils.uuid();
    section.sectionIndex = dto.sectionIndex || 1;
    section.isSectionTopicVisible = dto.isSectionTopicVisible || 0;
    section.sectionMainTopic = dto.sectionMainTopic || "";
    section.sectionSubTopic = dto.sectionSubTopic || "";

    const sec = await this.sectionModel.save(section);

    return this.utils.service.success(new SectionDto(sec));
  }

  async update_home_section(dto: SectionCreateDto, sectionId: string) {
    const section = await this.sectionModel.findOne({
      where: {
        sectionId
      }
    });
    if (!section) {
      return this.utils.service.fail("章节不存在");
    }

    section.sectionIndex = dto.sectionIndex || 1;
    section.isSectionTopicVisible = dto.isSectionTopicVisible || 0;
    section.sectionMainTopic = dto.sectionMainTopic || "";
    section.sectionSubTopic = dto.sectionSubTopic || "";

    const sec = await this.sectionModel.save(section);

    return this.utils.service.success(sec.sectionId);
  }

  async remove_home_section(sectionId: string) {
    const section = new BblHomeSection();
    section.sectionId = sectionId;
    const contents = await this.contentModel.find({
      where: { section }
    });
    await this.contentModel.remove(contents);
    await this.sectionModel.remove(section);

    return this.utils.service.success(sectionId);
  }

  async get_section_content_list(sectionId: string) {
    const res = await this.contentModel
      .createQueryBuilder("content")
      .leftJoinAndSelect("content.contentImg", "contentImg")
      .where("content.HOME_SECTION_ID = :sectionId", { sectionId })
      .orderBy("content.contentIndex", "ASC")
      .getMany();

    const result = res.map((d) => new ContentDto(d));

    return this.utils.service.success(result);
  }

  async add_section_content(dto: ContentCreateDto) {
    const content = new BblHomeContent();
    // 所属章节
    const section = new BblHomeSection();
    section.sectionId = dto.sectionId;
    content.section = section;
    content.contentId = this.utils.uuid();

    // 内容类型
    content.contentType = dto.contentType;

    content.contentIndex = dto.contentIndex || 1;

    // 根据内容类型，设置内容
    if (dto.contentType === 1) {
      // 文本
      content.contentText = dto.contentText;
    } else if (dto.contentType === 0) {
      const res = await this.attService.get_att_by_id(dto.attId);
      const contentImg = res.data;
      content.contentImg = contentImg;
      this.attService.tmp_to_uploads(contentImg);
    }

    const con = await this.contentModel.save(content);
    return this.utils.service.success(con);
  }

  async update_section_content(dto: ContentCreateDto, contentId: string) {
    const content = await this.contentModel
      .createQueryBuilder("content")
      .leftJoinAndSelect("content.contentImg", "contentImg")
      .where("content.contentId = :contentId", { contentId })
      .getOne();
    if (!content) {
      return this.utils.service.fail("内容不存在");
    }

    content.contentIndex = dto.contentIndex || 1;
    content.contentType = dto.contentType;
    if (content.contentType === 1) {
      content.contentText = dto.contentText;
    } else {
      if (content.contentImg.attId !== dto.attId) {
        await this.attService.remove(content.contentImg);
        const res = await this.attService.get_att_by_id(dto.attId);
        content.contentImg = res.data;
        await this.attService.tmp_to_uploads(res.data);
      }
    }

    this.contentModel.save(content);

    return this.utils.service.success(contentId);
  }

  async remove_section_content(contentId: string) {
    const content = await this.contentModel
      .createQueryBuilder("content")
      .leftJoinAndSelect("content.contentImg", "contentImg")
      .where("content.contentId = :contentId", { contentId })
      .getOne();

    if (!content) {
      return this.utils.service.fail("内容不存在");
    }

    if (content.contentType === 0) {
      await this.attService.remove(content.contentImg);
    }

    await this.contentModel.remove(content);

    return this.utils.service.success(contentId);
  }

  async get_section_list() {
    const builder = this.sectionModel
      .createQueryBuilder("section")
      .orderBy("section.sectionIndex", "ASC");

    const list = await builder.getMany();

    const data = list.map((d) => new SectionDto(d));

    return this.utils.service.success(data);
  }

  async add_home_banner(dto: BannerCreateDto) {
    const banner = new BblHomeBanner();

    banner.bannerId = this.utils.uuid();
    banner.bannerIndex = dto.bannerIndex || 1;
    const result = await this.attService.get_att_by_id(dto.attId);
    banner.bannerImg = result.data;
    const ban = await this.bannerModel.save(banner);
    await this.attService.tmp_to_uploads(result.data);
    return this.utils.service.success(ban.bannerId);
  }

  async get_banner_list() {
    const build = this.bannerModel
      .createQueryBuilder("banner")
      .leftJoinAndSelect("banner.bannerImg", "att")
      .orderBy("banner.bannerIndex", "ASC");

    const list = await build.getMany();
    const result = [];
    list.forEach((d) => {
      const banner: any = { ...d };
      banner.bannerImg = new AttachDto(d.bannerImg);
      result.push(banner);
    });

    return this.utils.service.success(result);
  }

  async update_home_banner(dto: BannerCreateDto, bannerId: string) {
    const build = this.bannerModel
      .createQueryBuilder("banner")
      .leftJoinAndSelect("banner.bannerImg", "att")
      .where("banner.bannerId = :bannerId", { bannerId });

    const banner = await build.getOne();
    banner.bannerIndex = dto.bannerIndex;

    if (dto.attId !== banner.bannerImg.attId) {
      await this.attService.remove(banner.bannerImg);
      const img = (await this.attService.get_att_by_id(dto.attId)).data;
      banner.bannerImg = img;
      await this.attService.tmp_to_uploads(img);
    }

    await this.bannerModel.save(banner);

    return this.utils.service.success(bannerId);
  }

  async remove_home_banner(bannerId: string) {
    const build = this.bannerModel
      .createQueryBuilder("banner")
      .leftJoinAndSelect("banner.bannerImg", "att")
      .where("banner.bannerId = :bannerId", { bannerId });

    const banner = await build.getOne();

    await this.attService.remove(banner.bannerImg);
    await this.bannerModel.remove(banner);

    return this.utils.service.success(bannerId);
  }

  async get_home_info() {
    const banners = (await this.get_banner_list()).data;
    const builder = this.sectionModel
      .createQueryBuilder("section")
      .leftJoinAndSelect("section.sectionContents", "sectionContents")
      .leftJoinAndSelect("sectionContents.contentImg", "contentImg")
      .orderBy("section.sectionIndex", "ASC")
      .addOrderBy("sectionContents.contentIndex", "ASC");

    const result = await builder.getMany();
    console.log(result);
    const sections = result.map((d) => {
      const data: any = { ...d };
      data.sectionContents.forEach((c) => {
        if (c.contentType === 0) {
          c.contentImg = new AttachDto(c.contentImg);
        }
      });
      return data;
    });

    return this.utils.service.success({ banners, sections });
  }

  async add_home_content(dto: ContentCreateDto) {}

  async get_home_section_list() {}
}
